package com.gzxw.mogublog.picture.util;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
@Slf4j
public class AliyunUtil {

    public String uploadFile(MultipartFile file) {
        String ednpoint = ConstantOssPropertiesUtils.EDNPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;

        //上传文件流
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(ednpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            String fileName=file.getOriginalFilename();
            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid= UUID.randomUUID().toString().replace("-","");
            fileName=uuid+fileName;

            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //   /2021/02/02/ 01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName=timeUrl+"/"+fileName;
            //调用方法实现上传
            //1.JPG
            ossClient.putObject(bucketName,fileName,inputStream);
            //关闭ossClient
            ossClient.shutdown();
            //https://xxxxx.oss-cn-beijing.aliyuncs.com/01.png
            //上传后路径
            String url="https://"+bucketName+"."+ednpoint+"/"+fileName;

            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

}
